package com.xhwl.centiotdata.suppliersystem.guangtuo.alarmhost.websocket;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.suppliersystem.guangtuo.alarmhost.websocket.handle.AlarmHostNotifyHandleFactory;
import com.xhwl.centiotdata.suppliersystem.guangtuo.alarmhost.websocket.handle.AlarmHostNotifyHandle;
import com.xhwl.common.exception.ApplicationException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.util.Map;
import java.util.concurrent.ExecutorService;

/**
 * @Author zhouyongzhou
 * @Date 2021/12/3 16:51
 * @Description
 */
@Slf4j
public class AlarmHostDeviceWebsocketClient extends BaseWebsocketClient {


    private URI url;

    public AlarmHostDeviceWebsocketClient(URI serverUri, Map<String, String> httpHeaders, ExecutorService workPoolScheduler) {
        super(serverUri, httpHeaders, workPoolScheduler);
        this.url = serverUri;
    }

    /**
     * 建立连接
     *
     * @param serverHandshake
     */
    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        log.info("onOpen()-------url:{}------", url);
        setConnectState(true);
    }

    /***
     * 接收消息
     * @param msg
     */
    @Override
    public void onMessage(String msg) {
        log.info("onMessage()-------url:{}-------result:{}", url, msg);
        if (StringUtils.isNotBlank(msg)) {
            JSONObject jsonObject = JSONObject.parseObject(msg);
            Object data = jsonObject.get("data");
            Object topic = jsonObject.get("topic");
            Object status = jsonObject.get("status");
            if (null == topic || topic.toString().trim().length() == 0) {
                log.error("【alarm-host websocket】path:{}; topic为空", url);
                throw new ApplicationException("");
            }
            if (null == status || status.toString().trim().length() == 0) {
                log.error("【alarm-host websocket】path:{}----topic:{}------status为空", url, topic);
                throw new ApplicationException("");
            }
            if (null == data || data.toString().trim().length() == 0) {
                log.error("【alarm-host websocket】path:{}----topic:{}------status-----data为空", url, topic, status);
                throw new ApplicationException("");
            }
            AlarmHostNotifyHandle invokeStrategy = AlarmHostNotifyHandleFactory.getInvokeStrategy(topic);
            invokeStrategy.handler(status.toString(), JSON.toJSONString(data));
        }
    }
}

